package kr.co.doriclassic.mypuppystory.alarmpuppy;

import java.text.ParseException;
import java.util.Calendar;
import kr.co.doriclassic.mypuppystory.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.ExpandableListView;
import android.widget.TextView;

public class AlarmPuppy extends Activity {
	// Array에서 쓸 변수
	private String[] jusaTitle;
	private String[] jusaContent;
	private String[] jusaCount;

	private ExpandableListView list;
	private View childView;

	// 차일드에서 사용할 것
	//private TextView tv2;
	private TextView tv3;
	private CheckBox cb;

	boolean[] mGroupClickState;
	int lastExpandedGroupPosition = -1;

	private Calendar calendar;
	private final static String EMPTY_DATA = "최종 접종일을\n선택하세요";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.network_stringarray);

		list = (ExpandableListView) findViewById(R.id.listView);
		list.setGroupIndicator(null);

		// 배열 리소스를 불러온다.
		jusaTitle = getResources().getStringArray(R.array.jusa_title);
		jusaContent = getResources().getStringArray(R.array.jusa_content);
		jusaCount = getResources().getStringArray(R.array.jusa_count);

		mGroupClickState = new boolean[jusaTitle.length];
		for (int i = 0; i < mGroupClickState.length; i++)
			mGroupClickState[i] = false;

		MyExpandableListAdapter adapter = new MyExpandableListAdapter(
				R.layout.alarm_row);
		list.setAdapter(adapter);

	}// onCreate

	class MyExpandableListAdapter extends BaseExpandableListAdapter {
		private View itemLayout;
		private int layout;
		private LayoutInflater inflater;

		public MyExpandableListAdapter(int layout) {
			this.layout = layout;
		}

		PreferenceManager pf = new PreferenceManager(AlarmPuppy.this);
		ChangeFormat cf = new ChangeFormat();
		Calendar c = Calendar.getInstance();

		int cyear = c.get(Calendar.YEAR);
		int cmonth = c.get(Calendar.MONTH);
		int cday = c.get(Calendar.DAY_OF_MONTH);
		private String lp;
		private TextView content;

		@Override
		public int getGroupCount() {
			return jusaTitle.length;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return 1;
		}

		@Override
		public Object getGroup(int groupPosition) {
			return jusaTitle[groupPosition];
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return jusaContent[groupPosition];
		}

		// 현재 차일드 카운트를 불러오는 부분
		public int getCount(int groupPosition, int childPosition) {
			return Integer.parseInt(jusaCount[groupPosition]);
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return true;// Collecton이면 false가변적
		}

		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			itemLayout = convertView;
			inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			// 처음 생성되었을 때, 나머지는 재활용(리스트뷰)
			itemLayout = inflater.inflate(layout, parent, false);

			content = (TextView) itemLayout.findViewById(R.id.content);

			content.setText(getGroup(groupPosition).toString());

			return itemLayout;
		}// getGroupView

		@Override
		public View getChildView(final int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			childView = convertView;
			inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			childView = inflater.inflate(R.layout.arraycontent, null);
			//tv2 = (TextView) childView.findViewById(R.id.jusacontent);
			//tv2.setText(getChild(groupPosition, childPosition).toString());
			// 프리프런스 저장(타이틀)
			pf.savePref("title" + groupPosition, getGroup(groupPosition)
					.toString());

			tv3 = (TextView) childView.findViewById(R.id.alarm_text);
			cb = (CheckBox) childView.findViewById(R.id.alarm_check);

			// 프리프런스 불러오기(저장된 값을 뿌려줌)
			cb.setChecked((boolean) pf.loadPref("check" + groupPosition, false));
			lp = (String) pf.loadPref("date" + groupPosition, EMPTY_DATA);
			if (!lp.equals(EMPTY_DATA)) {
				tv3.setText((CharSequence) lp);
				childView.findViewById(R.id.hidden_text).setVisibility(
						View.VISIBLE);
			} else {
				childView.findViewById(R.id.hidden_text).setVisibility(
						View.GONE);
			}

			// 체크박스
			cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {

					if (isChecked) {
						if (tv3.getText().equals(EMPTY_DATA)) {
							Toast.makeText(getApplicationContext(),
									"먼저 날짜를 선택해주세요.", Toast.LENGTH_SHORT)
									.show();
							cb.setChecked(false);
						} else {
							try {
								startAlarm(groupPosition, cf
										.stringToLong(pf.loadPref(
												"date" + groupPosition, "").toString()), 5);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							// 프리프런스 저장
							pf.savePref("check" + groupPosition, true);
						}
					} else {
						stopAlarm(groupPosition);
						// 프리프런스 저장
						pf.savePref("check" + groupPosition, false);
					}
				}

			});// onCheckedChangeListener

			childView.findViewById(R.id.date_btn).setOnClickListener(
					new OnClickListener() {
						@Override
						public void onClick(View v) {

							DatePickerDialog dialog = new DatePickerDialog(
									AlarmPuppy.this, new OnDateSetListener() {
										String sDate;
										String sCurrent;

										// 날짜가 정해졌다면
										@Override
										public void onDateSet(DatePicker view,
												int year, int monthOfYear,
												int dayOfMonth) {
											sCurrent = cf.dateToString(cyear,
													cmonth, cday);
											sDate = cf.dateToString(year,
													monthOfYear, dayOfMonth);
											childView
													.findViewById(
															R.id.hidden_text)
													.setVisibility(View.VISIBLE);
											try {
												// Log.d("currentDate",
												// cf.stringToLong(sCurrent)+"");
												// Log.d("selectDate",
												// cf.stringToLong(sDate)+"");
												if ((cf.stringToLong(sDate)) > cf
														.stringToLong(sCurrent)) {
													Toast.makeText(
															getApplicationContext(),
															"오늘 날짜보다 클 수 없습니다.",
															Toast.LENGTH_SHORT)
															.show();
												} else {
													tv3.setText(sDate);
													// 프리프런스 저장
													pf.savePref("date"
															+ groupPosition,
															sDate);
												}
											} catch (ParseException e) {
												e.printStackTrace();
											}
										}
									}, cyear, cmonth, cday);
							dialog.show();
						}
					});

			return childView;
		}// getChildView

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}// isChildSelectable

		// 나머지 열린 것 닫기
		@Override
		public void onGroupExpanded(int groupPosition) {
			// Log.e("", "LAST" + lastExpandedGroupPosition + ", CUR : "
			// + groupPosition);
			// TODO Auto-generated method stub
			// 그룹을 클릭했을때 열려져 있는 지 표시하는 화살표 아이콘 위/아래
			mGroupClickState[groupPosition] = !mGroupClickState[groupPosition];
//			// 그룹을 클릭했을때 이전그룹이 열려 있으면 닫음
//			if (lastExpandedGroupPosition != -1
//					&& lastExpandedGroupPosition != groupPosition) {
//				list.collapseGroup(lastExpandedGroupPosition);
//				mGroupClickState[lastExpandedGroupPosition] = false;
//			}// if

			lastExpandedGroupPosition = groupPosition;
			super.onGroupExpanded(groupPosition);
		}// onGroupExpanded
	}// MyExpandableListAdapter

	public void startAlarm(int unique_code, long last_time, int delay_time) {
		// unique_code=프리프런스 명, last_time=마지막 접종일, delay_time=지연할 시간(1년, 1개월),
		// type=1. 주기적으로 2. 특정 기간 내 주기적으로
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		// 예약에 의해 호출될 BR 지정
		Intent intent = new Intent(this, AlarmReceiver.class);
		// PendingIntent.getActivity(context,uniqueRQCODE, newIntent, 0);
		intent.putExtra("reqCode", unique_code);
		sendBroadcast(intent);

		PendingIntent sender = PendingIntent.getBroadcast(AlarmPuppy.this,
				unique_code, intent, 0);
		// 알람 시간. 10초후
		calendar = Calendar.getInstance();
		// 기준이 될 시간등록
		switch (unique_code) {
		case 0:// 매년마다
		case 1:// 매년마다
		case 2:// 매년마다
				// setAlarm(last_time, delay_time, 1000*60*60*24*12);
			setAlarm(am, sender, last_time, delay_time, 1000*60*60*24*12);
			break;
		case 3:// 개월마다
		case 4:// 특정기간 후 매달마다 몇번 반복
		case 5:// 특정기간 후 매달마다 몇번 반복
				// setAlarm(last_time, delay_time, 1000*60*60*24*6);
			setAlarm(am, sender, last_time, delay_time, 1000 * 50);
			break;

		}// switch

	}// startAlarm

	// 알람 설정
	private void setAlarm(AlarmManager am, PendingIntent sender,
			long last_time, int delay_time, long repeat_time) {
		calendar.setTimeInMillis(last_time);
		// 첫 알람이 울릴 시간
		calendar.add(Calendar.SECOND, delay_time);
		// 알람 등록
		am.set(AlarmManager.RTC, calendar.getTimeInMillis(), sender);
		// 반복해서 울릴 시간
		am.setRepeating(AlarmManager.ELAPSED_REALTIME,
				SystemClock.elapsedRealtime(), repeat_time, sender);
	}

	public void stopAlarm(int unique_code) {
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(this, AlarmReceiver.class);
		PendingIntent sender = PendingIntent.getBroadcast(AlarmPuppy.this,
				unique_code, intent, 0);
		am.cancel(sender);
	}
}// MainClass